package com.hjx.filter;

import com.hjx.servlet.LoginServlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.ConsoleHandler;
import java.util.regex.Pattern;

public class myFilter implements Filter{
    private ServletContext context=null;
    private String time=null;
    private boolean login_register_flag=false;
    private HttpSession session=null;
    private String path=null;
    private HttpServletResponse response=null;
    private boolean isIntercept=false;
//    使用线程实现自动显示时间
//    private static final ExecutorService pool = Executors.newFixedThreadPool(5);
//    public static final TaskTest me = new TaskTest();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        response=(HttpServletResponse)servletResponse;
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        String path=request.getRequestURI();
        System.out.println("path:"+path);
//        *:代表0次或多次匹配   . :代表匹配除\n和\r之外的字符
        System.out.println("islogin:"+Pattern.matches(".*login.*",path));
        System.out.println("isRegister:"+Pattern.matches(".*register.*",path));


        session=request.getSession();
        context=servletRequest.getServletContext();
        System.out.println("过滤器准备处理请求了");
//        处理乱码问题
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");

        isIntercept=getRequesPath(path);
//           如果请求不是登录和注册
        if(isIntercept){
            if (session.getAttribute("user")==null || session.getAttribute("user")==""){
                System.out.println("用户未登录！！，转发到登录页面");
                response.sendRedirect("/super/LoginValidate/login.jsp");
            }
        }else {
            System.out.println("请求不是后台index.jsp界面！！");
        }


        context=servletRequest.getServletContext();

//        每1s钟更新一次时间，并存入contex对象中
        showTime(context);


//        温馨提示
        String notice="为了正常浏览,请使用高版本浏览器！（IE10+)";
        context.setAttribute("notice",notice);

        filterChain.doFilter(servletRequest,servletResponse);

    }


    /*
            schedule(TimerTask task, long delay, long period)
            第一个为定时任务，根据业务需要重写TimerTask的run方法即可；
            第二个为延时启动，单位毫秒；
            第三个位多久运行一次，单位毫秒；


     */


//    时间改用js来显示了，因为不知道js中如何 servletContext中的数据  ${applicationScope['time']}：这种做法不行，会报错！！
    public void showTime(final ServletContext context){
        new Timer().schedule(new TimerTask() {
            @Override
//            重写抽象类的run方法  1s钟执行一次
            public void run() {
                try {
                   if(getTime()!=null && getTime()!=""){
                       //        存入时间
                       context.setAttribute("time",getTime());
                   }else {
                       System.out.println("time为空");
                   }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },0,1000);
    }


    public String getTime(){
        //        System.currentTimeMillis():时间戳
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        time=formatter.format(date);
        return time;
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁了！！");
    }

    public void getUserMessage(HttpServletRequest request, HttpServletResponse response)throws Exception{
        HttpSession session=request.getSession();
        if(session.getAttribute("user")==null || session.getAttribute("user")==null){
            System.out.println("用户未登录");
            response.sendRedirect("/super/LoginValidate/login.jsp");
        }
    }

//    获取页面请求路径
    public boolean getRequesPath(String path){
//        如果请求路径中包含index 就拦截   返回true代表需要被拦截
        if(Pattern.matches(".*index.*",path)){
            isIntercept=true;
            return  isIntercept;
        }
        return false;

    }

}
